package com.secretum;
// Copyright (C) 2001, Internet Designers Ltd. All rights reserved.
// This program is free software and may be distributed under the terms
// of the GNU Lesser General Public License, Version 2.1.
// This program comes with ABSOLUTELY NO WARRANTY.
//
// Neil Winton (neil.winton@idl-bt.com)
//
// $Id: CTest.java,v 1.4 2001/06/21 14:53:35 wintonn Exp $

import java.io.*;
import com.secretum.zebedee.*;


/**
 * This is a simple demonstration of the Zebedee client-side API.
 */

public class CTest
{
    public static void main(String args[]) throws Exception
    {
	// Create a "master" instance so that we can set some
	// common options and share the key re-use table. if this
	// was going to be a "one shot" connection we would not
	// bother with a separare master, just use the ZBDTunnelClient
	// instance directly.

	// Tunnel to a server on "localhost"

	ZBDTunnelClient master = new ZBDTunnelClient("localhost");

	// Set some arbitrary parameters.
	// We will chose a strange key size and a small buffer to
	// force multiple messages to be read/written.

	master.setKeySize(161);
	master.setBufferSize(10);
	master.setLogger(new ZBDBasicLogger(1));

	// Clone a new instance from the master.
	// You could also use master.clone() if you wanted.

	ZBDTunnelClient t1 = new ZBDTunnelClient(master);

	// Request a connection to the daytime port

	t1.connect("localhost", 13);

	// Retrieve the input stream and read (up to) 100 bytes
	// from it. Closing the stream will end the tunnel.

	InputStream s = t1.getInputStream();

	byte[] b = new byte[100];
	int num = 0;
	while ((num = s.read(b)) > 0)
	{
	    System.out.print(new String(b, 0, num));
	}
	s.close();


	// Now create a second tunnel. This time we will direct
	// traffic to the "echo" port. We will this time get the
	// input and output streams and wrap them in standard Java
	// i/o wrapper classes -- just to show that we can.

	ZBDTunnelClient t2 = new ZBDTunnelClient(master);
	t2.connect("localhost", ZBDServiceLookup.lookup("echo", "tcp"));

	InputStreamReader in = new InputStreamReader(t2.getInputStream());
	PrintWriter out = new PrintWriter(t2.getOutputStream());

	// Write out a message and then read it back ...

	char[] cbuf = new char[100];
	String msg = "Hello, World!\r\n";
	out.print(msg);
	out.flush();
	int total = 0;

	while (total < msg.length() && (num = in.read(cbuf, 0, 100)) > 0)
	{
	    System.out.print(new String(cbuf, 0, num));
	    total += num;
	}

	in.close();
	out.close();
    }
}
